package cn.jdemo.juc.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @date 2020/12/1
 */
public class DemoAsync {

    private static final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);

    public static void main(String[] args) throws Exception {
        DemoAsync.test01();
    }

    /**
     * 执行顺序:(acceptEither方法，主体哪个执行快，参数是哪个)没有返回值
     * pool-1-thread-1 : num1
     * 我是pool-1-thread-3 : return_value01
     * pool-1-thread-2 : num2
     */
    public static void test01()throws Exception{
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "begin...");
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "end...");
        }, es);

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "begin...");
            try {
                Thread.sleep(200L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "end...");
        }, es);

        CompletableFuture.allOf(future1, future2).get(250L,TimeUnit.MILLISECONDS);

        es.shutdown();
    }

}
